<?php

class FileHandler{
	private $path;

	private $replyFileName = 'reply';
	private $lastIdFileName = 'last_id';
	private $messagesFileName = 'messages';
	private $loginFileName = 'login';

	public function __construct($path = null){ 
		$this->path = $path;
	}

	private function resolvePath($path){
		if($path == null) $path = $this->path;
		else if($this->path != null) $path = $this->path.$path;

		return $path;
	}

	public function createDirectory($path=null,$resolve=true){
		if($resolve) $path = $this->resolvePath($path);

		mkdir($path);
	}

	public function setPath($path=null){
		$this->path = $path;
	}

	public function clearFile($path=null,$resolve=true){
		if($resolve) $path = $this->resolvePath($path);

		$this->createFile($path,'',false);
	}

	public function createFile($path=null,$content='',$resolve=true){
		if($resolve) $path = $this->resolvePath($path);

		file_put_contents($path, $content);
	}

	public function getFileContent($path=null,$clear=false,$resolve=true){
		if($resolve) $path = $this->resolvePath($path);
		
		$content = @file_get_contents($path);

		if($clear && $content != '') $this->clearFile($path,false);

		return $content;
	}

	public function entryExists($path=null,$resolve=true){
		if($resolve) $path = $this->resolvePath($path);

		if(is_file($path) || is_dir($path)) return true;
		return false;
	}

	public function appendToFiles($line,$path,$exception=array(),$resolve=true){
		if($resolve) $path = $this->resolvePath($path);
		
		if(is_file($path)) $this->appendLine($path,$line,false);
		else{
			if($directory = opendir($path)){
		
			    while (false !== ($file = readdir($directory))) {
			    	$filePath = $path.$file;
			        if(is_file($filePath)){
			        	if(!isset($exception[$file])){
				        	$this->appendLine($filePath, $line,false);
			        	}		        	
			        }
			    }
			}
		}
	}

	public function appendLine($path,$line,$resolve=true){
		if($resolve) $path = $this->resolvePath($path);

		$content = file_get_contents($path);
		if($content != '') $line = "\n".$line;

		$content .= $line;
			        	
		file_put_contents($path, $content);
	}

	public function deleteEntry($path=null,$resolve=true){
		if($resolve) $path = $this->resolvePath($path);

		if(is_file($path)) $this->deleteFile($path, false);
		else $this->deleteDirectory($path);
	}

	public function deleteFile($path=null,$resolve=true){
		if($resolve) $path = $this->resolvePath($path);

		return unlink($path);
	}

	public function deleteDirectory($path=null, $resolve=true){
		if($resolve) $path = $this->resolvePath($path);
	
		if($directory = opendir($path)){
		    while (false !== ($file = readdir($directory))) {
		    	$filePath = "$path/$file";
		        if(is_file($filePath)){
		        	$this->deleteFile($filePath,false);
		        }
		    }
		}

		return rmdir($path);
	}

}

?>	